﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Media3D;

using HelixToolkit.Wpf;
using EQEmu.Maps;
using EQEmu.Display3D;

namespace EQEmu.Maps.Display3D
{
    public class MapDisplay3D : IDisposable, IViewConstrainer
    {
        private readonly Map _map;
        private readonly Model3D _group = new Model3DGroup();
        
        public Model3D Model
        {
            get { return _group; }
        }
        
        public void UpdateAll()
        {
            if (_map == null || _map.Triangles == null) return;

            Model3DGroup group = Model as Model3DGroup;

            group.Children.Clear();

            List<Face> faces = _map.Triangles;            
            MeshBuilder builder = new MeshBuilder();

            foreach (Face face in faces)
            {
                Point3D p1 = new Point3D(face.v1.x,face.v1.y,face.v1.z);
                Point3D p2 = new Point3D(face.v2.x,face.v2.y,face.v2.z);
                Point3D p3 = new Point3D(face.v3.x,face.v3.y,face.v3.z);

                if (_constraints != null)
                {
                    if (!_constraints.IsPointWithinConstraints(p1) ||
                        !_constraints.IsPointWithinConstraints(p2) ||
                        !_constraints.IsPointWithinConstraints(p3))
                    {
                        continue;
                    }
                }

                builder.AddTriangle(p1, p2, p3);                   
            }
            group.Children.Add(new GeometryModel3D(builder.ToMesh(), Materials.Gray));                        
        }

        public MapDisplay3D(Map map)
        {
            _map = map;
            UpdateAll();
        }

        protected virtual void Dispose(bool disposeAll)
        {
            _constraints = null;
        }

        public void Dispose()
        {
            Dispose(true);
        }

        private ViewConstraints _constraints = null;

        public void UpdateView(ViewConstraints constraints)
        {
            _constraints = constraints;
            UpdateAll();
        }
    }
}
